package com.gitee.openviducn.inspector.rest;

import com.gitee.openviducn.inspector.cdr.repository.BaseCDRRepository;
import com.gitee.openviducn.inspector.common.ResponseResult;
import com.gitee.openviducn.inspector.domain.vo.request.QueryCDRRequest;
import com.gitee.openviducn.inspector.domain.vo.request.WebhookCDRRequest;
import com.gitee.openviducn.inspector.enums.CDREventEnum;
import com.google.common.collect.Sets;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @Author: https://gitee.com/wesleyOne
 * @Date: 04.19 2020
 */
@Slf4j
@Api(tags = "CDR记录接口")
@RequestMapping("/cdr")
@RestController
public class CDRController {

    @Resource
    private BaseCDRRepository cdrRepository;

    @ApiOperation("获取指定session的CDR记录")
    @PostMapping("/records")
    public ResponseResult<List<WebhookCDRRequest>> query(@Validated @RequestBody QueryCDRRequest queryCDRRequest) {

        List<String> events = queryCDRRequest.getEvents();
        Set<String> eventSets = Sets.newHashSet();
        if (CollectionUtils.isEmpty(events)) {
            CDREventEnum[] values = CDREventEnum.values();
            for (CDREventEnum cdr : values) {
                eventSets.add(cdr.getCode());
            }
        } else {
            for (String cdr : events) {
                if (Objects.nonNull(CDREventEnum.getByCode(cdr))) {
                    eventSets.add(cdr);
                }
            }
        }
        List<WebhookCDRRequest> list = cdrRepository.queryBySessionIdAndEventsBetween(queryCDRRequest.getSessionId(), eventSets);
        list.forEach(cdr -> {
            if (Objects.nonNull(cdr.getTimestamp())) {
                cdr.setTimestampStr(DateFormatUtils.format(cdr.getTimestamp(), DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.getPattern()));
            }
            if (Objects.nonNull(cdr.getStartTime())) {
                cdr.setStartTimeStr(DateFormatUtils.format(cdr.getStartTime(), DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.getPattern()));
            }
        });
        return ResponseResult.success(list);
    }
}
